package qqhfpay

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/pay/base"
	"io"
	"log"
	"net/http"
)

type Factory struct {
}

func (p *Factory) CreatePay(config base.Config) base.Payment {
	return &QQHFPay{
		Url:        config.Url,
		SecretKey:  config.SecretKey,
		NotifyUrl:  config.NotifyUrl,
		MerchantId: config.MerchantId,
	}
}

type QQHFPay struct {
	Url        string
	SecretKey  string
	NotifyUrl  string
	MerchantId string
}

type QQHFResponse struct {
	Code string `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		SysOrderId string  `json:"sysOrderId"` // 通道订单号
		Status     string  `json:"status"`     // 交易状态（SUCCESS,NOTPAY-表示成功，其他都是失败，FAIL-失败，CLOSED-关闭）
		CheckStand string  `json:"checkStand"` // 收银台支付链接
		Amount     float64 `json:"amount"`     // 请求收款金额，金额 * 100
		Fee        float64 `json:"fee"`        // 手续费，金额 * 100
		RealAmount float64 `json:"realAmount"` // 实际到账金额，代码，金额 * 100
	} `json:"data"`

	Error string `json:"error"`
}

// Pay 代收订单创建
func (qqh *QQHFPay) Pay(ctx context.Context, req map[string]any) (resp base.PayResponse, err error) {
	params := make(map[string]any)

	// 第三方必传参数
	params["merchantNo"] = qqh.MerchantId
	params["version"] = "1.0"
	params["merchantOrderId"] = req["orderNo"]
	params["channelCode"] = "NGASVIPDS"
	params["amount"] = req["amount"]
	params["currency"] = "NGN"
	params["subject"] = req["orderNo"]
	// if req["email"] == nil {
	//	err = errors.New("email is required")
	//	return
	// }
	// if req["userName"] == nil {
	//	err = errors.New("userName is required")
	//	return
	// }
	// if req["mobileNo"] == nil {
	//	err = errors.New("mobileNo is required")
	//	return
	// }
	// todo
	params["email"] = "test@coolgame.world"
	params["userName"] = "zhangsan"
	params["mobileNo"] = "15982360145"
	params["expireTime"] = "60"

	// 第三方可选参数
	params["notifyUrl"] = qqh.NotifyUrl
	_, ok := req["bankInfo"] // 格式为JSON字符串
	if ok {
		params["bankInfo"] = req["bankInfo"]
	}
	_, ok = req["remark"]
	if ok {
		params["remark"] = req["remark"]
	}
	_, ok = req["extInfo"] // 格式为JSON字符串
	if ok {
		params["extInfo"] = req["extInfo"]
	}

	// 生成签名
	params["sign"], err = GenerateSignatureOfQqhf(params, qqh.SecretKey)
	if err != nil {
		return
	}

	// 请求第三方接口
	url := qqh.Url + "/payin/unifiedorder.do"
	qqhResp, err := qqh.send(url, params)
	if err != nil {
		return
	}

	_result, _ := json.Marshal(qqhResp)
	resp = base.PayResponse{
		Url:     qqhResp.Data.CheckStand,
		OrderNo: qqhResp.Data.SysOrderId,
		Result:  string(_result),
	}

	return
}

// 发送请求，处理返回数据
func (qqh *QQHFPay) send(payUrl string, data map[string]interface{}) (*QQHFResponse, error) {
	var (
		qqhResp = &QQHFResponse{}
		err     error
	)
	// Convert data to JSON
	jsonData, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}

	// Create a new HTTP request
	req, err := http.NewRequest(http.MethodPost, payUrl, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, err
	}
	// Set the appropriate headers
	req.Header.Set("Content-Type", "application/json")

	// Create a new HTTP client and send the request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		return nil, errors.New(resp.Status)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	fmt.Println(string(body))
	log.Println(string(body))
	// Parse the JSON response
	err = json.Unmarshal(body, &qqhResp)
	if err != nil {
		return nil, err
	}

	// 第三方结果处理
	// 失败
	if qqhResp.Code != "000" {
		return nil, errors.New(qqhResp.Msg)
	}
	// 成功
	if qqhResp.Data.Status == "SUCCESS" || qqhResp.Data.Status == "NOTPAY" {
		return qqhResp, nil
	}

	// 失败
	return nil, errors.New(qqhResp.Data.Status)
}
